package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.RecommendUser;
import com.tanhua.manage.domain.vo.PageResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 通过用户id 查询今日佳人
     *
     * @param
     * @return
     */
    @Override
    public RecommendUser todayBest(Long userId) {

        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        RecommendUser todayBest = mongoTemplate.findOne(query, RecommendUser.class);
        return todayBest;
    }

    /**
     * 通过用户id查询推荐佳人分页查询
     * @param loginUserId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findPage(Long page, Long pagesize, Long loginUserId) {
        Query query = new Query(Criteria.where("toUserId").is(loginUserId));
        //统计总数
        long total = mongoTemplate.count(query,RecommendUser.class);
        List<RecommendUser> recommendUserList = new ArrayList<>();
        if (total>0){
            query.skip((page-1)*pagesize).limit(pagesize.intValue());
            recommendUserList = mongoTemplate.find(query,RecommendUser.class);
        }

        return PageResult.pageResult(page,pagesize,recommendUserList,total);
    }

    /**
     * 通过登陆用户与佳人id查询两者的缘分值
     *
     * @param loginUserId 登陆用户id
     * @param userId      佳人id
     * @return
     */
    @Override
    public Double queryForScore(Long loginUserId, Long userId) {
        //1.构建查询条件
        Query query = new Query(Criteria.where("toUserId").is(loginUserId).and("userId").is(userId));
        //2.查询。【注意】在推荐好友表，必须存在佳人记录
        RecommendUser recommendUser = mongoTemplate.findOne(query,RecommendUser.class);
        if(null == recommendUser){
            return RandomUtils.nextDouble(60,80);
        }
        return recommendUser.getScore();
    }
}
